package com.glsc.ngateway.oaflow.utils;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Title: DocUtils
 * @Description: 文件类。
 * @author: 张宁
 * @version: 1.0.0
 * @date: 2020/12/21 16:29
 */
public class DocUtils {
    private static final Logger logger = LoggerFactory.getLogger(DocUtils.class);


    public static String saveFile(byte[] file, String filePath, String fileName) throws IOException {

        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(filePath + fileName);
            FileChannel fileChannel = fileOutputStream.getChannel();
            ByteBuffer buf = ByteBuffer.wrap(file);
            while (fileChannel.write(buf) != 0) {
            }
        } catch (IOException e) {
            return "Exception";
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return filePath + fileName;
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public static String renameToUUID(String fileName) {
        return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }


    public static String tranformStyle(String source) throws UnsupportedEncodingException {
        char[] arr = source.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            char temp = arr[i];
            if (isChinese(temp)) {
                sb.append(URLEncoder.encode("" + temp, "UTF-8"));
                continue;
            }
            sb.append(arr[i]);
        }
        return sb.toString();
    }

    public static String repalceSpecialWord(String url) throws UnsupportedEncodingException {
        url = url.replace(" ", "%20").replace("?", "%3F").replace("#", "%23")
                .replace("&", "%26").replace("=", "%3D").replace("+", "%2B");


        return url;
    }


    /**
     * 判断是不是中文字符
     *
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {

        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);

        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;

    }


    /**
     * @param urlStr   下载文件URL字符串
     * @param savePath
     * @return
     * @throws IOException
     * @Description 通过URL下载附件，URL可以不需要转移urlencode，因为调用下载接口HttpUtil.downloadFile
     */
    public static File downLoadFromUrl(String urlStr, String fileName, String batchId, String savePath) {
        try {
            File downloadFile = new File(savePath + batchId + File.separator + fileName);
            HttpUtil.downloadFile(urlStr, downloadFile);
            return downloadFile;
        } catch (Exception e) {
            logger.error("下载网络文件失败：{}={}", fileName, urlStr, e);
            return null;
        }
    }


    /**
     * @param url
     * @return
     * @Description 通过URL获取附件文件名称
     */
    public static String getFileNameFromUrl(String url) {
        String name = new Long(System.currentTimeMillis()).toString() + ".X";
        int index = url.lastIndexOf("/");
        if (index > 0) {
            name = url.substring(index + 1);
            if (name.trim().length() > 0) {
                return name;
            }
        }
        return name;
    }


    public static void main(String[] args) {

        String url = "http://10.197.32.32:8080/filesystem/downDir/1607481204481632599/系统架构图-Page-5.jpg";
        File result = downLoadFromUrl(url,"系统架构图-Page-5.jpg","uudi12121212", "D:/download_files/");
        List<File> finalList = new ArrayList<File>();
        finalList.add(result);
        //ZipUtils.toZips(finalList,"D:\\test.zip");
    }


    public static <T> List<T> linkedMapTypeListToObjectList(List<T> lst, Class<T> responseType) {
        // 处理linkedHashMap
        lst = JSONObject.parseArray(JSONObject.toJSONString(lst)).toJavaList(responseType);
        return lst;
    }


//    public static List linkedMapTypeListToObjectList(Object detailList, Class<Map> mapClass) {
//    }
}

